namespace MathExtensions {
    // 扩展 Math 接口，声明 easeInOutQuad 方法
    interface Math {
        easeInOutQuad(t: number, b: number, c: number, d: number): number;
    }

    // 实现 easeInOutQuad 方法
    (Math as any).easeInOutQuad = function (t: number, b: number, c: number, d: number) {
        t /= d / 2;
        if (t < 1) {
            return (c / 2) * t * t + b;
        }
        t--;
        return (-c / 2) * (t * (t - 2) - 1) + b;
    };
}

// requestAnimationFrame for Smart Animating http://goo.gl/sx5sts
const requestAnimFrame = (function (): (callback: FrameRequestCallback) => number {
    return (
        window.requestAnimationFrame ||
        // 这里使用标准的 requestAnimationFrame 替代非标准的前缀方法
        function (callback: FrameRequestCallback) {
            return window.setTimeout(callback, 1000 / 60);
        }
    );
})();

/**
 * Because it's so fucking difficult to detect the scrolling element, just move them all
 * @param {number} amount
 */
function move(amount: number) {
    document.documentElement.scrollTop = amount;
    const bodyParent = document.body.parentNode as HTMLElement | null;
    if (bodyParent) {
        bodyParent.scrollTop = amount;
    }
    document.body.scrollTop = amount;
}

function position(): number {
    const bodyParent = document.body.parentNode as HTMLElement | null;
    return (
        document.documentElement.scrollTop ||
        (bodyParent?.scrollTop || 0) ||
        document.body.scrollTop
    );
}

/**
 * @param {number} to
 * @param {number} duration
 * @param {Function} callback
 */
export const scrollTo = (to: number, duration?: number, callback?: () => void) => {
    const start = position();
    const change = to - start;
    const increment = 20;
    let currentTime = 0;
    duration = typeof duration === "undefined" ? 500 : duration;
    const animateScroll = function () {
        // increment the time
        currentTime += increment;
        // find the value with the quadratic in-out easing function
        const val = (Math as any).easeInOutQuad(currentTime, start, change, duration);
        // move the document.body
        move(val);
        // do the animation unless its over
        if (currentTime < duration) {
            requestAnimFrame(animateScroll);
        } else {
            if (callback) {
                // the animation is done so lets callback
                callback();
            }
        }
    };
    animateScroll();
};
